import type { ISectionClient, ISectionGroup, IUser } from '@/interfaces';
import Image from 'next/image';
import Link from 'next/link';
import { getCover, getUserAvatar } from '@/lib/tool';
import classNames from 'classnames';
import Nodata from '@/app/[locale]/common/nodata/nodata';
import { useContext } from 'react';
import { SectionPageContext } from '@/contexts/section';
import { AppContext } from '@/contexts/app';

export default function SectionH5Page() {
  const {
    source: { sections },
    translatedFields,
  } = useContext(SectionPageContext)!;
  const data = sections;
  const sectionGroups = data
    .filter((item) => !!item.sectionGroup)
    .filter(
      (item, index, array) =>
        array.findIndex(
          (value) => value.sectionGroup!.id === item.sectionGroup!.id,
        ) === index,
    )
    .map((item) => {
      const sectionGroup = item.sectionGroup!;
      const _sections: ISectionClient[] = [];
      data.forEach((value) => {
        if (value.sectionGroup?.id === sectionGroup.id) {
          _sections.push(value);
        }
      });
      sectionGroup.sections = _sections;
      return sectionGroup;
    });
  const otherSections = data.filter((item) => !item.sectionGroup);

  return (
    <div className="card rounded-5 border-0">
      <div className="card-body vstack gap-4 overflow-hidden">
        {sectionGroups.map((item, index) => {
          return <Item key={item.id} item={item} index={index} />;
        })}

        {otherSections.length > 0 &&
          [
            {
              id: -1,
              name: translatedFields.otherContent,
            },
          ].map((item, index) => {
            return (
              <Item
                key={item.id}
                item={item as ISectionGroup}
                index={index}
                firstRowLine={sectionGroups.length > 0}
                vstack={sectionGroups.length === 0}
                showNav={sectionGroups.length > 0}
                items={otherSections}
              />
            );
          })}

        {sectionGroups.length === 0 && otherSections.length === 0 && <Nodata />}
      </div>
    </div>
  );
}

const Item = ({
  item,
  index,
  firstRowLine,
  items,
  vstack,
  showNav = true,
}: {
  item: ISectionGroup;
  index: number;
  firstRowLine?: boolean;
  items?: ISectionClient[];
  vstack?: boolean;
  showNav?: boolean;
}) => {
  return (
    <div className="row gap-4">
      {firstRowLine && (
        <div
          className="col-12 yw-bg w-100"
          style={{ height: '0.5rem', transform: 'scale(1.1)' }}
        ></div>
      )}
      {!firstRowLine && index !== 0 && (
        <div
          className="col-12 yw-bg w-100"
          style={{ height: '0.5rem', transform: 'scale(1.1)' }}
        ></div>
      )}

      {showNav && (
        <div className="col-12 user-select-none d-flex align-items-center justify-content-between">
          <div className="h4">{item.name}</div>
          <div className="text-secondary">
            <i className="bi bi-arrow-right fs-4"></i>
          </div>
        </div>
      )}

      <div
        className={classNames(
          'col-12 pb-3 gap-4',
          vstack
            ? 'vstack'
            : 'd-flex align-items-center flex-nowrap text-nowrap overflow-x-auto',
        )}
      >
        {(items ? items : item.sections!).map((sectionItem) => {
          return (
            <div
              key={sectionItem.id}
              className="vstack gap-4 shadow-sm px-4 py-2 rounded-4"
            >
              <Cover id={sectionItem.id} cover={sectionItem.cover} />

              <Admins
                id={sectionItem.id}
                items={(sectionItem as ISectionClient).admins}
              />

              <div className="vstack gap-2">
                <Name id={sectionItem.id} name={sectionItem.name} />

                <Overview overview={sectionItem.overview} />
              </div>

              <End id={sectionItem.id} />
            </div>
          );
        })}
      </div>
    </div>
  );
};

const Cover = ({ id, cover }: { id: number; cover: string | undefined }) => {
  const appContext = useContext(AppContext);
  const metadata = appContext.metadata!;
  const env = metadata.env;

  return (
    <>
      {cover && (
        <div>
          <Link href={`/sections/${id}`}>
            <Image
              className="rounded object-fit-contain w-auto"
              src={getCover(cover, metadata)}
              width={150}
              height={112}
              alt="cover"
              placeholder="blur"
              blurDataURL={env.APP_BLUR_DATA_URL}
            />
          </Link>
        </div>
      )}
    </>
  );
};

const Admins = ({ id, items = [] }: { id: number; items?: IUser[] }) => {
  const appContext = useContext(AppContext);
  const metadata = appContext.metadata!;
  const env = metadata.env;

  return (
    <>
      {items.length > 0 && (
        <div className="position-relative w-100" style={{ height: 48 }}>
          {items.slice(0, 5).map((item, index) => {
            return (
              <div
                key={item.id}
                className="position-absolute"
                style={{
                  left: index * 33,
                  zIndex: index + 1,
                }}
              >
                <Link
                  title={`${item.alias}(${item.id})`}
                  className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
                  href={`/users/${item.id}`}
                >
                  <Image
                    className="rounded-circle"
                    src={getUserAvatar(item, metadata).smallAvatarUrl}
                    alt="avatar"
                    title={item.alias ? `${item.alias} (ID. ${item.id})` : ''}
                    placeholder="blur"
                    blurDataURL={env.APP_BLUR_DATA_URL}
                    width={48}
                    height={48}
                  />
                </Link>
              </div>
            );
          })}

          {items.length > 5 && (
            <div
              className="position-absolute fs-5 link-secondary"
              style={{ left: 198, top: 6 }}
            >
              <Link
                className="text-decoration-none text-decoration-underline-hover link-secondary"
                href={`/sections/${id}`}
              >
                +{items.length - 5}
              </Link>
            </div>
          )}
        </div>
      )}
    </>
  );
};

const Name = ({ id, name }: { id: number; name: string }) => {
  return (
    <Link
      href={`/sections/${id}`}
      className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
    >
      {name}
    </Link>
  );
};

const Overview = ({ overview }: { overview: string | undefined }) => {
  return (
    <>
      {overview && (
        <div
          style={{
            width: 112,
          }}
          className="text-truncate text-secondary"
          dangerouslySetInnerHTML={{
            __html: overview,
          }}
        ></div>
      )}
    </>
  );
};

const End = ({ id }: { id: number }) => {
  const { translatedFields } = useContext(SectionPageContext)!;

  return (
    <div>
      <Link
        href={`/sections/${id}`}
        className="text-decoration-none position-relative"
      >
        {translatedFields.enterContent}
        <i
          className="bi bi-arrow-up-short align-middle d-inline-block fs-4"
          style={{ transform: 'rotate(45deg)' }}
        ></i>
      </Link>
    </div>
  );
};
